/** 用户信息页 **/
import React, { useState } from "react";
import { Form, Input, Button, Radio, message } from "antd";
import { useDispatch, useSelector } from "react-redux";

import style from "./index.module.less";
import { ChangePasswordReqI } from "../../types/api";
import {
  cellPhoneValidator,
  emailValidator,
  testPasswordStrength,
} from "../../utils/index";
import { RootStateI, UserI } from "../../types/system";
import { updateProfile } from "../../api/system";
import { CustomResponse } from "../../api/http_class";
import { setUserAction } from "../../store/actions";

function Profile(): JSX.Element {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false); // 是否正在提交中
  const [editable] = useState<boolean>(true);
  const user = useSelector((state: RootStateI) => state.user);
  const dispatch = useDispatch();

  /**
   * 提交表单且数据在前端验证成功后 执行登录
   */
  const handleFinish = () => {
    setLoading(true);
    form.validateFields().then(
      (values: ChangePasswordReqI) => {
        console.log(values);
        updateProfile(values).then(
          (res: CustomResponse<UserI>) => {
            console.log(res.data);
            message.success("更新成功");
            dispatch(setUserAction(res.data));
            // form.resetFields();
            form.setFieldsValue(res.data);
          },
          (err) => {
            console.log(err);
            message.error(`提交失败: ${err.detail}`);
          }
        );
        setLoading(false);
      },
      (errors) => {
        console.log(errors);
        setLoading(false);
      }
    );
  };

  return (
    <div className={style.profile}>
      <div className={style.content}>
        <Form
          form={form}
          name={"roleForm"}
          labelCol={{ span: 8 }}
          onFinish={handleFinish}
          autoComplete="off"
          scrollToFirstError
          disabled={!editable}
          initialValues={user}
        >
          <Form.Item
            name="id"
            label="id"
            hidden={true}
            rules={[
              {
                required: false,
                message: "请输入id",
              },
            ]}
          >
            <Input disabled={true} />
          </Form.Item>
          <Form.Item
            name="username"
            label="用户名"
            hasFeedback
            rules={[
              {
                required: true,
                message: "请输入用户名",
              },
              {
                min: 3,
                message: "用户名最短3位",
              },
              {
                max: 32,
                message: "用户名最长32位",
              },
            ]}
          >
            <Input disabled={true} />
          </Form.Item>
          <Form.Item
            name="cellphone"
            label="手机号"
            hasFeedback
            rules={[{ validator: cellPhoneValidator }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            hasFeedback
            rules={[
              {
                validator: emailValidator,
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="sex"
            label="性别"
            rules={[
              {
                required: true,
                message: "请输入性别",
              },
            ]}
          >
            <Radio.Group>
              <Radio value={0}>未知</Radio>
              <Radio value={1}>男</Radio>
              <Radio value={2}>女</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="oldPassword"
            label="原用户密码"
            rules={[
              {
                required: false,
                message: "请输入原用户密码",
              },
            ]}
          >
            <Input.Password
              // autoComplete="off"无效，只使用new-password能解决Chrome自动填充问题
              // 但不解决点击密码框展示存的账号列表，蜜罐用于保险
              autoComplete="new-password"
            />
          </Form.Item>
          <Form.Item
            name="password"
            dependencies={["oldPassword"]}
            label="新用户密码"
            rules={[
              ({ getFieldValue }) => ({
                validator(_, value) {
                  // 如果原密码和新密码均为空则不改密码
                  if (!getFieldValue("oldPassword") && !value) {
                    return Promise.resolve();
                  } else if (!getFieldValue("oldPassword") && value) {
                    return Promise.reject(new Error("请先输入原密码"));
                  }
                  // 有密码时校验密码强度
                  if (value && value.length > 0) {
                    if (testPasswordStrength(value) < 3) {
                      return Promise.reject(
                        new Error(
                          "密码强度不够，建议至少6位，数字、大写字母、小写字母及其它字符至少包含3种"
                        )
                      );
                    }
                    return Promise.resolve();
                  } else {
                    return Promise.reject(new Error("请输入新密码"));
                  }
                },
              }),
            ]}
            hasFeedback
          >
            <Input.Password
              // autoComplete="off"无效，只使用new-password能解决Chrome自动填充问题
              // 但不解决点击密码框展示存的账号列表，蜜罐用于保险
              autoComplete="new-password"
            />
          </Form.Item>
          <Form.Item
            name="passwordAgain"
            label="再次输入新密码"
            dependencies={["password", "id"]}
            hasFeedback
            rules={[
              ({ getFieldValue }) => ({
                validator(_, value) {
                  // 校验两次新密码是否一致
                  if (!value || getFieldValue("password") === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error("两次输入的新密码不匹配"));
                },
              }),
            ]}
          >
            <Input.Password
              // autoComplete="off"无效，只使用new-password能解决Chrome自动填充问题
              // 但不解决点击密码框展示存的账号列表，蜜罐用于保险
              autoComplete="new-password"
            />
          </Form.Item>

          <Form.Item>
            <Button
              disabled={loading}
              type="primary"
              htmlType="submit"
              style={{ width: "100%" }}
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}

export default Profile;
